package com.yinhai;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.yinhai.model.FileInfo;
import com.yinhai.tool.FileTools;
import com.yinhai.tool.UsualTools;

public class FileDeal extends HttpServlet {

	
	public FileDeal() {
		super();
	}

	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	

	/**
	 * The service method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post and get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 * purpose：该方法主要用于获取文件操作相关参数，根据参数调用相关方法进行处理
	 */
	public void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setCharacterEncoding("utf-8");
		request.setCharacterEncoding("utf-8");
		
		//String mt=request.getParameter("mt");

		
		String mainGo=request.getParameter("mainGo");
		String mt=request.getParameter("mt");
		String textPath=request.getParameter("file");
		if("fileMain".equals(mainGo))
		{
			if("findRoots".equals(mt))//显示分区
			{
				this.showFileRoots(request, response);
			}
			else if("find".equals(mt))
			{
				
				this.showFiles(request, response);
			}
			else if("delete".equals(mt))
			{
				this.deleteFiles(request, response);
				this.showFiles(request, response);
			}
			else if("createDir".equals(mt))
			{
				this.createDir(request, response);
				this.showFiles(request, response);
			}
			else if("cut".equals(mt))
			{
				this.cutFiles(request, response);
				this.showFiles(request, response);
			}
			else if("parse".equals(mt))
			{
				this.pasteFiles(request, response);
				this.showFiles(request, response);
			}
			else if("copy".equals(mt))
			{
				this.cutFiles(request, response);
				this.showFiles(request, response);
			}
			else if("zip".equals(mt))
			{
				this.zipFiles(request, response);
				this.showFiles(request, response);
			}
			else if("unzip".equals(mt))
			{
				this.unzipFiles(request, response);
				this.showFiles(request, response);
			}
			else if("reName".equals(mt))
			{
				this.reNameFile(request, response);
				this.showFiles(request, response);
			}
			else if("down".equals(mt))
			{
				this.downFiles(request, response);//输出后response会提交
				//this.showFiles(request, response);
			}
			else if("downFile".equals(mt))
			{
				this.downFile(request, response);
			}
			else if("upLoad".equals(mt))
			{
				
			}
		
		}
		else{
			this.upLoad(request, response);
		}
		
		//request.setAttribute("aaa", "test");
		//System.out.println(request.getContextPath()+"/caizh/FILE/FileMain.jsp");
		
	
		
			
		try
		{
		request.getRequestDispatcher("/caizh/FILE/FileMain.jsp").forward(request, response);
		}catch(IllegalStateException e)
		{
			System.out.println("response已输出 提交");
		}
		//request.getRequestDispatcher("../caizh/FILE/FileMain.jsp").forward(request, response);
		//response.sendRedirect("../caizh/FILE/FileMain.jsp");
	}
	
	public void init() throws ServletException {
		// Put your code here
	}
	
	/**
	 * purpose show file roots
	 * @param request
	 * @param response
	 */
	public void showFileRoots(HttpServletRequest request, HttpServletResponse response)
	{
		File[] fs=null;
		if(UsualTools.isLinux)
		{
			fs=new File("/").listFiles();
		}
		else
		{
			fs=File.listRoots();
		}
		request.setAttribute("pathDirectory","/");
		
		List s=FileTools.getInstance().returnFiles(fs);
		
		request.setAttribute("sss",s);
		
		this.showDirGuide(request, response);
	}
	
	public void showFiles(HttpServletRequest request, HttpServletResponse response)
	{
		try{
		String path=UsualTools.getInstance().changeCode(request.getParameter("file"));

		
		File f=new File(path);
		//request.setAttribute("pathDirectory", f.getAbsolutePath().replaceAll("\\\\", "/")!=""?f.getAbsolutePath().replaceAll("\\\\", "/"):"/");
		request.setAttribute("pathDirectory", f.getAbsolutePath()!=""?f.getAbsolutePath():"/");
		File[] fs=f.listFiles();
		
		List s=FileTools.getInstance().returnFiles(fs);
		request.setAttribute("sss",s);
		}catch(Exception e){
			System.out.println("showFiles is fail");
		}
		
		this.showDirGuide(request, response);
	}
	
	public void showDirGuide(HttpServletRequest request,
			HttpServletResponse response) {
		File[] fs = File.listRoots();
		File f = null;
		FileInfo fi=null;
		List s = FileTools.getInstance().returnFiles(fs);
		String sps[] = { "user.home", "java.home", "user.dir", "real.path" };// sun.boot.library.path,"catalina.home"
		for (int i = 0; i < sps.length; i++) {
			String value = null;
			switch (i) {
			case 3:
				value = request.getRealPath("/");
				break;
			default:
				value = System.getProperty(sps[i]);
			}
			f = new File(value);
			fi=FileTools.getInstance().returnFileInfo(f);
			fi.setFileName(sps[i]);
			s.add(fi);
		}

		request.setAttribute("DirGudie", s);
	}
	
// public List returnFiles(HttpServletRequest request, HttpServletResponse
// response,File [] fs)
//	{
//		List s=new ArrayList();
//		
//		FileInfo fi=null;
//		File f=null;
//		FileTools ft=FileTools.getInstance();
//		for (int i=0;i<fs.length;i++)
//		{
//			
//			f=(File)fs[i];
//			
//			fi=new FileInfo();
//			if(f.exists())
//			{
//				
//			fi.setFileName(ft.getDisplayName(f));
//			fi.setFileSpace(ft.getFileSpace(f));
//			fi.setFileType(ft.getFileType(f));
//			fi.setModifyDate(ft.getModifyDate(f));
//			fi.setProperty(ft.getFileProperty(f));
//			}
//			else
//			{
//			fi.setFileName(ft.getDisplayName(f));
//			}
//			fi.setFilePath(ft.getFileUrlPath(f));
//
//			
//		//	System.out.println(f.getAbsolutePath().replaceAll("\\\\", "/"));
//			
//			s.add(fi);
//			f=null;
//			fi=null;
//			
//			
//		}
//		
//		
//		return s;
//
//	}
//	
	/**
	 * purpose 用于删除目录及其文件
	 */
	public void deleteFiles(HttpServletRequest request,
			HttpServletResponse response)
	{
		boolean b=false;
		String error=null;
		String [] ss=request.getParameterValues("f");
		File f=null;
		for(int i=0;i<ss.length;i++)
		{
		  try {
			f=new File(URLDecoder.decode(ss[i],"utf-8"));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		  FileTools.getInstance().deleteFiles(f);//删除功能暂不开放，等有需求去掉注释，程序已经支持
		  
		}
		
		if(!b)
		{
			request.setAttribute("error", "文件或目录删除失败");
		}
		
	}
	
	/**
	 * purpose 创建目录
	 * @param request
	 * @param response
	 */
	public void createDir(HttpServletRequest request,
			HttpServletResponse response)
	{
		try
		{
		String dirName=request.getParameter("dirname");
        String path=UsualTools.getInstance().changeCode(request.getParameter("file"));
		File f=new File(path);
		File file=new File(f,dirName);
		file.mkdirs();
		}
		catch(Exception e)
		{
			System.out.println("createDir is fail");
		}
		//request.setAttribute("pathDirectory", f.getAbsolutePath()!=""?f.getAbsolutePath():"/");
	}
	/**
	 * 此方法用于需要被剪切的文件
	 * @param request
	 * @param response
	 */
	public void cutFiles(HttpServletRequest request,
			HttpServletResponse response)
	{
		String [] ss=request.getParameterValues("f");
	    List<File> list=new ArrayList<File>();
		File f=null;
		for(int i=0;i<ss.length;i++)
		{
		
		try {
			f=new File(URLDecoder.decode(ss[i],"utf-8"));
			list.add(f);
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		  
		}
		request.getSession().setAttribute("list", list);
		if("cut".equals(request.getParameter("mt")))
		{
			request.getSession().setAttribute("file.cut", true);
		}
		else if("copy".equals(request.getParameter("mt")))
		{
			request.getSession().setAttribute("file.copy", true);
		}
		
	}
	/**
	 * 此方法用于粘贴被剪切或者复制的文件
	 * @param request
	 * @param response
	 */
	public void pasteFiles(HttpServletRequest request,
			HttpServletResponse response)
	{
		String path=UsualTools.getInstance().changeCode(request.getParameter("file"));
		File d=new File(path);//目标目录
		List<File> list=(ArrayList<File>)request.getSession().getAttribute("list");
		if(list!=null)
		{
		for(int i=0;i<list.size();i++)
		{
			
			FileTools.getInstance().copyFiles(list.get(i), d);
			if(request.getSession().getAttribute("file.cut")!=null)
		    {
		    	FileTools.getInstance().deleteFiles(list.get(i));
		    }
		    
		}
		}
		request.getSession().removeAttribute("file.cut");
		request.getSession().removeAttribute("file.copy");
		request.getSession().removeAttribute("list");
	    
	}
	/**
	 * purpse 用于压缩文件
	 * @param request
	 * @param response
	 */
	public void zipFiles(HttpServletRequest request,
			HttpServletResponse response)
	{
		String [] ss=request.getParameterValues("f");
		File f =null;
	    try 
	    {
	    	f=new File(URLDecoder.decode(ss[0],"utf-8")+".zip");
	    	if(f.exists())
	    	{
	    		f=new File(URLDecoder.decode(ss[0],"utf-8")+"z"+System.currentTimeMillis()+".zip");
	    	}
	     	
	    } catch (UnsupportedEncodingException e) 
	    {
	    	// TODO Auto-generated catch block
	    	e.printStackTrace();
	    }
	    try {
			FileTools.getInstance().zip(ss, new FileOutputStream(f));
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
			
	   
	}
	
	/**
	 * purpse 用于解压文件
	 * @param request
	 * @param response
	 */
	public void unzipFiles(HttpServletRequest request,
			HttpServletResponse response)
	{
		String path=UsualTools.getInstance().changeCode(request.getParameter("file"));
		File d=new File(path);//目标目录
		String [] ss=request.getParameterValues("f");
		File f=null;
		for(int i=0;i<ss.length;i++)
		{
		  try {
			f=new File(URLDecoder.decode(ss[i],"utf-8"));
			FileTools.getInstance().unZip(f, d);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		}
	}
	
	/**
	 * purpse 用于重命名文件
	 * @param request
	 * @param response
	 */
	public void reNameFile(HttpServletRequest request,
			HttpServletResponse response)
	{
		String path=UsualTools.getInstance().changeCode(request.getParameter("file"));
		String dirName=request.getParameter("dirname");
		File d=new File(path);//目标目录
		File f=null;
		String [] ss=request.getParameterValues("f");
		if(ss.length<2)
		{
			try {
				f=new File(URLDecoder.decode(ss[0],"utf-8"));
				f.renameTo(new File(d,dirName));
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		else
		{
			for(int i=0;i<ss.length;i++)
			{
				try 
				{
					f=new File(URLDecoder.decode(ss[i],"utf-8"));
					f.renameTo(new File(d,dirName+"("+i+")"));
				} 
				catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
			}
	  }
	}
	
	
	/**
	 * purpse 用于批量下载文件或者目录
	 * @param request
	 * @param response
	 */
	public void downFiles(HttpServletRequest request,
			HttpServletResponse response) throws IOException,UnsupportedEncodingException
	{
		response.setContentType("application/octet-stream");//caizh 使用这个contentType的话访问页面的时候浏览器就会开启下载框对其内容进行下载
		response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode("file.zip","UTF-8"));
		
	    
	    String [] ss=request.getParameterValues("f");
		File f=null;
		for(int i=0;i<ss.length;i++)
		{
			f=new File(URLDecoder.decode(ss[i],"utf-8"));
		}
		FileTools.getInstance().zip(ss,response.getOutputStream());
			
	    return;
	}
	
	/**
	 * purpse 用于批量下载文件或者目录
	 * @param request
	 * @param response
	 */
	public void downFile(HttpServletRequest request,
			HttpServletResponse response) throws IOException,UnsupportedEncodingException
	{
		String path=UsualTools.getInstance().changeCode(request.getParameter("file"));//通过连接传送的字符串，编码是TOMCAT的编码，需转码
		
		
		File f=new File(path);
		response.setContentType("application/octet-stream");//caizh 使用这个contentType的话访问页面的时候浏览器就会开启下载框对其内容进行下载
		response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(f.getName(),"UTF-8"));
		
	    long len=f.length();
	    String range=request.getHeader("Range");
	    FileInputStream fis=new FileInputStream(f);
	    if(range!=null)//类似于断点续传，具体可看blogjava
	    {
	      response.setStatus(206);
	      response.setHeader("Content-Range",range+"/"+len);
	      String arr[]=range.substring(6).split("-");
	      long start=arr[0].length()<1?0:Long.parseLong(arr[0]);
	      long stop=arr[1].length()<1?len:Long.parseLong(arr[1])+1;
	      fis.skip(start);
	      len=stop-start;
	    }
	    response.setContentLength((int)len);
	    OutputStream os=response.getOutputStream();
	    byte by[]=new byte[8192];
	    int value=0;
	    try
	    {
	      while((value=fis.read(by))!=-1)
	      {
	        os.write(by,0,value);
	      }
	    }finally
	    {
	      fis.close();
	      os.close();
	    }
	    return;
	}
	
	/**
	 * purpose 上传文件至服务器
	 */
	public void upLoad(HttpServletRequest request,
			HttpServletResponse response) throws IOException,UnsupportedEncodingException
    {
		File dir=null;//目标路径
		//为该请求创建一个DiskFileItemFactory对象，通过它来解析请求。执行解析后，所有的表单项目都保存在一个List中。
		DiskFileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		try {
			// 得到所有的文件
			List<FileItem> items = upload.parseRequest(request);
			Iterator<FileItem> i = items.iterator();
			while (i.hasNext()) 
			{
	              FileItem fi = (FileItem) i.next();
	              String fieldName = fi.getFieldName();//表单提交的字段
	              if(fieldName!=null)
	              {
	            	  if("file".equals(fieldName))
	            	  {
	            		  
	            		  dir=new File(fi.getString());//生成目录文件
	            	  }
	              }
	              String fileName = fi.getName();
	              if (fileName != null) 
	              {
	            	      
	            	  File savedFile = new File(dir,fileName.substring(fileName.lastIndexOf(File.separator)));
		              //System.out.println(savedFile.getAbsolutePath());
	            	  fi.write(savedFile);
	                  
	              }
	       }

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		//下面是文件重新搜寻
		try{

			
			File f=dir;
			//request.setAttribute("pathDirectory", f.getAbsolutePath().replaceAll("\\\\", "/")!=""?f.getAbsolutePath().replaceAll("\\\\", "/"):"/");
			request.setAttribute("pathDirectory", f.getAbsolutePath()!=""?f.getAbsolutePath():"/");
			File[] fs=f.listFiles();
			
			List s=FileTools.getInstance().returnFiles(fs);
			request.setAttribute("sss",s);
			}catch(Exception e){
				System.out.println("showFiles is fail");
			}
			
			this.showDirGuide(request, response);

	}
	 
}
